import { UserOutlined } from '@ant-design/icons';
import ProLayout, { BasicLayoutProps } from '@ant-design/pro-layout';
import { Avatar } from 'antd';
import React from 'react';
import { Link, useHistory, useLocation } from 'react-router-dom';

import logo from '@/assets/logo.svg';
import UserModel from '@/models/user';
import { getToken } from '@/utils/cookies';

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const { pathname } = useLocation();
  const history = useHistory();
  const { asideMenus } = UserModel();

  const loginPath = '/login';

  return (
    <div style={{ height: '100vh' }}>
      <ProLayout
        {...props}
        logo={logo}
        onMenuHeaderClick={() => history.push('/')}
        layout="mix"
        navTheme="light"
        headerTheme="light"
        fixedHeader={true}
        fixSiderbar={true}
        onPageChange={() => {
          const hasToken = getToken();
          if (!hasToken && pathname !== loginPath) {
            history.push(loginPath);
          }
        }}
        rightContentRender={() => (
          <div>
            <Avatar shape="square" size="small" icon={<UserOutlined />} />
          </div>
        )}
        menuItemRender={(item, dom) => {
          if (!item.path || pathname === item.path) {
            return dom;
          }
          return <Link to={item.path}>{dom}</Link>;
        }}
        splitMenus={true}
        route={{ routes: asideMenus }}
      />
    </div>
  );
};

export default BasicLayout;
